<template>
  <div class="data-security-supply-container" v-loading="loadingAll">
    <div class="container-box">
      <div class="title">
        <div class="title-text">数据在线供给</div>
      </div>
      <div class="top-cards">
        <a-card class="summary-card" v-for="(card, idx) in topCards" :key="idx" :bordered="false">
          <div class="card-inner card-item">
            <div class="card-left">
              <div class="card-title">
                <span>{{ card.title }}</span>
                <span class="sub">{{ card.sub || '' }}</span>
              </div>
              <div class="card-value">
                <template v-if="card.ratio">
                  <span>{{ onlineStatistics[card.prop] || 0 }}%&nbsp;|&nbsp;{{ onlineStatistics[card.prop2] || 0 }}%</span>
                </template>
                <template v-else>
                  <span>{{ onlineStatistics[card.prop] || 0 }}&nbsp;|&nbsp;{{ onlineStatistics[card.prop2] || 0 }}</span>
                  <span class="unit">{{ card.unit }}</span>
                </template>
              </div>
            </div>
            <!-- <div class="card-right">
              <img :src="card.icon" alt="" class="icon" v-if="card.icon" />
            </div> -->
          </div>
        </a-card>
      </div>
      <div class="middle-charts">
        <a-card class="chart-box">
          <div class="title">
            <div class="title-text">数据共享供给服务量统计【TOP10】</div>
            <div class="title-action">
              <!-- <span class="text">供数方</span> -->
              <!--<a-select
                v-model:value="onlineLeft.selValue"
                :options="onlineLeft.options"
                :allow-clear="true"
                style="width: 150px"
                placeholder="请选择"
                @change="(val) => fetchOnlineSupplyTest('online', val)"
              ></a-select>-->
            </div>
          </div>
          <div class="chart-content">
            <BarChart :chart-data="onlineLeft.chartData" :key="1"></BarChart>
          </div>
        </a-card>
        <a-card class="chart-box">
          <div class="title">
            <div class="title-text">数据开发测试服务量统计【TOP10】</div>
            <div class="title-action">
              <!-- <span class="text">供数方</span> -->
              <!-- <a-select
                v-model:value="onlineRight.selValue"
                :options="onlineLeft.options"
                :allow-clear="true"
                style="width: 150px"
                placeholder="请选择"
                @change="(val) => fetchOnlineSupplyTest('online_v2', val)"
              ></a-select> -->
            </div>
          </div>
          <div class="chart-content">
            <BarChart :chart-data="onlineRight.chartData" :key="2"></BarChart>
          </div>
        </a-card>
      </div>
    </div>
    <div class="divider"></div>

    <div class="container-box">
      <div class="title">
        <div class="title-text">数据离线供给</div>
      </div>
      <div class="top-cards">
        <a-card class="summary-card" v-for="(card, idx) in topCards02" :key="idx" :bordered="false">
          <div class="card-inner">
            <div class="card-left">
              <div class="card-title">
                <span>{{ card.title }}</span>
                <span class="sub"></span>
              </div>
              <div class="card-value">
                <template v-if="card.ratio">
                  <span>{{ offlineStatistics[card.prop] || 0 }}%</span>
                </template>
                <template v-else>
                  <span>{{ offlineStatistics[card.prop] }}{{ card.unit }}{{ offlineStatistics[card.prop2] ? ' | ' + offlineStatistics[card.prop2] : '' }}{{ card.unit02 }}</span>
                </template>
              </div>
            </div>
            <!-- <div class="card-right">
              <img :src="card.icon" alt="" class="icon" v-if="card.icon" />
            </div> -->
          </div>
        </a-card>
      </div>
      <div class="middle-charts">
        <a-card class="chart-box">
          <div class="title">
            <div class="title-text">最近一周服务情况统计</div>
          </div>
          <div class="chart-content">
            <line-chart :chart-data="lastestServiceStatistics" :key="'line' + 1"></line-chart>
          </div>
        </a-card>
        <a-card class="chart-box">
          <div class="title">
            <div class="title-text">敏感数据类型分布</div>
          </div>
          <div class="chart-content">
            <pie-chart :chart-data="sensitiveDataTypes" :key="'pie' + 2"></pie-chart>
          </div>
        </a-card>
      </div>
    </div>
    <div class="divider"></div>
    <div class="container-box">
      <div class="title">
        <div class="title-text">数据工具箱</div>
      </div>
      <div class="top-cards">
        <a-card class="summary-card" v-for="(card, idx) in topCards03" :key="idx" :bordered="false">
          <div class="card-inner">
            <div class="card-left">
              <div class="card-title">
                <span>{{ card.title }}</span>
                <span class="sub"></span>
              </div>
              <div class="card-value">
                <span>{{ toolboxStatistics[card.prop] || '0' }}{{ card.unit }}</span>
                <!-- <span class="unit">{{ card.unit }}</span> -->
              </div>
            </div>
            <!-- <div class="card-right">
              <img :src="card.icon" alt="" class="icon" v-if="card.icon" />
            </div> -->
          </div>
        </a-card>
      </div>
      <div class="middle-charts">
        <a-card class="chart-box">
          <div class="title">
            <div class="title-text">服务量统计（按文件类型）【TOP10】</div>
          </div>
          <div class="chart-content">
            <pie-chart :chart-data="toolboxFileStatistics" :key="'pie' + 1" sub-title="冗余功能调用"></pie-chart>
          </div>
        </a-card>
        <a-card class="chart-box">
          <div class="title">
            <div class="title-text">最近一周服务情况统计</div>
          </div>
          <div class="chart-content">
            <line-chart :chart-data="toolboxLastestServiceStatistics" :key="'line' + 2" :color-list="['rgba(250,200,50)', 'rgba(57,121,255)', 'rgba(50,199,50)', 'rgba(131,142,154)']"></line-chart>
          </div>
        </a-card>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, watch } from 'vue'
import icon01 from '@/assets/img/dataSecuritySupply/icon01.png'
import icon02 from '@/assets/img/dataSecuritySupply/icon02.png'
import icon03 from '@/assets/img/dataSecuritySupply/icon03.png'
import icon04 from '@/assets/img/dataSecuritySupply/icon04.png'
import icon05 from '@/assets/img/dataSecuritySupply/icon05.png'
import icon06 from '@/assets/img/dataSecuritySupply/icon01-1.png'
import icon07 from '@/assets/img/dataSecuritySupply/icon01-2.png'
import icon08 from '@/assets/img/dataSecuritySupply/icon01-3.png'
import icon09 from '@/assets/img/dataSecuritySupply/icon05-1.png'
import icon10 from '@/assets/img/dataSecuritySupply/icon04-1.png'
import BarChart from './barChart.vue'
import LineChart from './lineChart.vue'
import PieChart from './pieChart.vue'
import {
  getOnlineStatistics,
  getListTaskUseDataParty,
  getOnlineSupplyTest,
  getOfflineStatistics,
  getOfflineLastestServiceStatistics,
  getOfflineSensitiveDataTypes,
  getToolboxStatistics,
  getToolboxFileStatistics,
  getToolboxLastestServiceStatistics
} from '@/api/data-security-supply'
const loadingAll = ref(false)
//数据在线供给数据统计明细
const onlineStatistics = ref<any>({})
const topCards = ref([
  {
    title: '供给任务数',
    unit: '个',
    sub: '(数据共享/开发测试)',
    icon: icon01,
    prop: 'taskSupplyNum',
    prop2: 'taskTestNum',
    bgColor: 'linear-gradient(180deg, rgba(231, 249, 249), rgba(243, 252, 251), rgba(255, 255, 255))'
  },
  {
    title: '供给文件数',
    unit: '个',
    sub: '(数据共享/开发测试)',
    icon: icon02,
    prop: 'fileSupplyNum',
    prop2: 'fileTestNum',
    bgColor: 'linear-gradient(to bottom, rgba(215, 238, 246),rgba(243, 250, 252), rgba(255, 255, 255))'
  },
  {
    title: '数据量',

    unit: 'MB',
    sub: '(数据共享/开发测试)',
    icon: icon03,
    prop: 'dataSupplyDiskSpace',
    prop2: 'dataTestDiskSpace',
    bgColor: 'linear-gradient(to bottom, rgba(229, 242, 255), rgba(245, 250, 255), rgba(255, 255, 255))'
  },
  {
    title: '数据脱敏成功率',
    ratio: true,
    unit: '',
    sub: '(数据共享/开发测试)',
    icon: icon04,
    prop: 'successRateSupply',
    prop2: 'successRateTest',
    bgColor: 'linear-gradient(to bottom, rgba(221, 225, 247), rgba(242, 244, 252), rgba(255, 255, 255))'
  },
  {
    title: '数据水印成功率',
    ratio: true,
    unit: '',
    sub: '(数据共享/开发测试)',
    icon: icon05,
    prop: 'watermarkSuccessRateSupply',
    prop2: 'watermarkSuccessRateTest',
    bgColor: 'linear-gradient(to bottom, rgba(254, 242, 207),rgba(254, 2450, 226), rgba(255, 255, 255))'
  }
])
//数据共享供给服务量统计【TOP10】
const onlineLeft = ref<any>({
  options: [],
  selValue: null,
  chartData: {
    xAxisData: [],
    seriesData: []
  }
})

//数据开发测试服务量统计【TOP10】
const onlineRight = ref<any>({
  options: [],
  selValue: null,
  chartData: {
    xAxisData: [],
    seriesData: []
  }
})

/** 数据离线供给 */
const offlineStatistics = ref<any>({})
const topCards02 = ref<any[]>([
  {
    title: '文件上传服务量',
    unit: '次',
    icon: icon06,
    prop: 'fileUploadNum',
    bgColor: 'linear-gradient(to bottom, rgba(215, 238, 246),rgba(243, 250, 252), rgba(255, 255, 255))'
  },
  {
    title: '文件下载服务量',
    unit: '次',
    icon: icon07,
    prop: 'fileDownloadNum',
    bgColor: 'linear-gradient(to bottom, rgba(215, 238, 246),rgba(243, 250, 252), rgba(255, 255, 255))'
  },
  {
    title: '文件量',

    unit: '个',
    unit02: 'G',
    icon: icon08,
    prop: 'fileNum',
    prop2: 'fileDiskSpace',
    bgColor: 'linear-gradient(to bottom, rgba(229, 242, 255), rgba(245, 250, 255), rgba(255, 255, 255))'
  },
  {
    title: '数据水印成功率',
    icon: icon04,
    prop: 'dataWatermarkRate',
    ratio: true,
    bgColor: 'linear-gradient(to bottom, rgba(221, 225, 247), rgba(242, 244, 252), rgba(255, 255, 255))'
  },
  {
    title: '数据脱敏成功率',
    icon: icon05,
    prop: 'dataMaskRate',
    ratio: true,
    bgColor: 'linear-gradient(to bottom, rgba(239, 229, 198),rgba(249, 244, 232), rgba(254, 254, 253))'
  }
])
/**最近一周服务情况统计 */
const lastestServiceStatistics = ref<any>({
  xAxisData: [],
  seriesData: [
    {
      name: '文件上传',
      data: []
    },
    {
      name: '文件下载',
      data: []
    }
  ]
})
/**敏感工具箱统计（工具箱) */
const toolboxStatistics = ref<any>({})
const topCards03 = ref([
  {
    title: '数据水印',
    unit: '次',
    prop: 'dataWatermark',
    icon: icon09,
    bgColor: 'linear-gradient(to bottom, rgba(217, 238, 246),rgba(242, 249, 252), rgba(254, 255, 255))'
  },
  {
    title: '数据脱敏（服务量）',
    value: '251',
    unit: '次',
    icon: icon04,
    prop: 'dataSensitive',
    bgColor: 'linear-gradient(to bottom, rgba(218, 223, 246), rgba(241, 242, 252), rgba(254, 254, 255))'
  },
  {
    title: '敏感数据监测',
    unit: '次',
    prop: 'sensitiveDataDetection',
    icon: icon03,
    bgColor: 'linear-gradient(to bottom, rgba(231, 242, 255), rgba(245, 250, 255), rgba(251, 253, 255))'
  },
  {
    title: '水印溯源',
    prop: 'watermarkTrace',
    unit: '次',
    icon: icon10,
    bgColor: 'linear-gradient(to bottom, rgba(230, 242, 255), rgba(243, 249, 255), rgba(251, 253, 255))'
  },
  {
    title: '数据水印成功率',
    prop: 'dataWatermarkRate',
    unit: '%',
    icon: icon05,
    bgColor: 'linear-gradient(to bottom, rgba(239, 229, 198),rgba(249, 244, 232), rgba(254, 254, 253))'
  }
])
/**服务类统计【按文件类型】(TOP10)（工具箱） */
const toolboxFileStatistics = ref<any>([])
/***最近一周服务情况统计（工具箱） */
const toolboxLastestServiceStatistics = ref<any>({
  xAxisData: [],
  seriesData: [
    {
      name: '数据水印',
      data: []
    },
    {
      name: '敏感数据监测',
      data: []
    },
    {
      name: '水印溯源',
      data: []
    },
    {
      name: '数据脱敏'
    }
  ]
})

//敏感数据类型分布
const sensitiveDataTypes = ref<any>([])

/**
 * 包裹 initAllData，并控制 loadingAll
 */
const loadAllData = async () => {
  loadingAll.value = true
  try {
    await initAllData()
  } finally {
    loadingAll.value = false
  }
}
const initAllData = async () => {
  const requests = [
    fetchOnlineStatistics(),
    fetchListTaskUseDataParty('online'),
    fetchListTaskUseDataParty('online_v2'),
    fetchOnlineSupplyTest('online'),
    fetchOnlineSupplyTest('online_v2'),
    fetchOfflineStatistics(),
    fetchOfflineLastestServiceStatistics(),
    fetchOfflineSensitiveDataTypes(),
    fetchToolboxStatistics(),
    fetchToolboxFileStatistics(),
    fetchToolboxLastestServiceStatistics()
  ]

  const results = await Promise.allSettled(requests)

  results.forEach((r, idx) => {
    if (r.status === 'rejected') {
      console.error(`接口执行失败：`, (r as PromiseRejectedResult).reason)
    }
  })
}
/**  在线供给统计（在线） */
const fetchOnlineStatistics = async () => {
  try {
    const res = await getOnlineStatistics()
    onlineStatistics.value = res.data
  } catch (error) {
    console.error('获取在线统计失败：', error)
  }
}
/**  获取任务下拉用数方 */
const fetchListTaskUseDataParty = async (dataType: string) => {
  try {
    const res = await getListTaskUseDataParty(dataType)
    const list = res.data.map((item: string) => {
      return { value: item, label: item }
    })
    if (dataType === 'online') {
      onlineLeft.value.options = list
    } else {
      onlineRight.value.options = list
    }
  } catch (error) {
    console.error('获取任务下拉用数方失败：', error)
  }
}
/*** 数据共享供给、开发测试服务量统计(TOP10)（在线） */
const fetchOnlineSupplyTest = async (dataType: string, useDataParty?: any) => {
  try {
    const res = await getOnlineSupplyTest({ data: { dataType, useDataParty } })

    let chartData: any = {
      xAxisData: res.data ? res.data.map((item: any) => item.taskName) : [],
      seriesData: [
        {
          name: '成功',
          data: res.data ? res.data.map((item: any) => item.successRate) : []
        },
        {
          name: '失败',
          data: res.data ? res.data.map((item: any) => item.failRate) : []
        }
      ]
    }
    if (dataType === 'online') {
      onlineLeft.value.chartData = chartData
    } else {
      onlineRight.value.chartData = chartData
    }
  } catch (error) {
    console.error('获取数据共享供给、开发测试服务量统计(TOP10)（在线）失败：', error)
  }
}
/**离线供给统计（离线） */
const fetchOfflineStatistics = async () => {
  try {
    const res = await getOfflineStatistics()
    offlineStatistics.value = res.data
  } catch (error) {
    console.error('获取离线统计失败：', error)
  }
}
/**最近一周服务情况统计（离线） */
const fetchOfflineLastestServiceStatistics = async () => {
  try {
    const res = await getOfflineLastestServiceStatistics()
    lastestServiceStatistics.value.xAxisData = res.data.map((item: any) => item.dateTime)
    lastestServiceStatistics.value.seriesData = [
      {
        name: '文件上传',
        data: res.data.map((item: any) => item.uploadNum)
      },
      {
        name: '文件下载',
        data: res.data.map((item: any) => item.downloadNum)
      }
    ]
  } catch (error) {
    console.error('获取最近一周服务情况统计（离线）失败：', error)
  }
}
/**敏感数据类型分布（离线） */
const fetchOfflineSensitiveDataTypes = async () => {
  try {
    const res = await getOfflineSensitiveDataTypes()
    sensitiveDataTypes.value =
      res.data.map((item: any) => {
        return {
          name: item.fileType,
          value: item.fileNum
        }
      }) || []
  } catch (error) {
    console.error('获取敏感数据类型分布（离线）失败：', error)
  }
}
/**敏感工具箱统计（工具箱 */
const fetchToolboxStatistics = async () => {
  try {
    const res = await getToolboxStatistics()
    toolboxStatistics.value = res.data
  } catch (error) {
    console.error('获取敏感工具箱统计（工具箱）失败：', error)
  }
}
/**服务类统计【按文件类型】(TOP10)（工具箱） */
const fetchToolboxFileStatistics = async () => {
  try {
    const res = await getToolboxFileStatistics()
    toolboxFileStatistics.value =
      res.data.map((item: any) => {
        return {
          name: item.fileType,
          value: item.fileNum
        }
      }) || []
  } catch (error) {
    console.error('获取服务类统计【按文件类型】(TOP10)（工具箱）失败：', error)
  }
}
/**最近一周服务情况统计（工具箱） */
const fetchToolboxLastestServiceStatistics = async () => {
  try {
    const res = await getToolboxLastestServiceStatistics()
    toolboxLastestServiceStatistics.value.xAxisData = res.data.map((item: any) => item.dateTime) || []
    toolboxLastestServiceStatistics.value.seriesData = [
      {
        name: '数据水印',
        data: res.data.map((item: any) => item.watermarkNum) || []
      },
      {
        name: '敏感数据监测',
        data: res.data.map((item: any) => item.detectionNum) || []
      },
      {
        name: '水印溯源',
        data: res.data.map((item: any) => item.traceNum) || []
      },
      {
        name: '数据脱敏',
        data: res.data.map((item: any) => item.maskNum) || []
      }
    ]
  } catch (error) {
    console.error('获取最近一周服务情况统计（工具箱）失败：', error)
  }
}
onMounted(() => {
  loadAllData()
})
</script>
<style lang="scss" scoped>
.data-security-supply-container {
  height: 100%;
  overflow: auto;
  .container-box {
    padding: 0 16px 20px;
    .title {
      display: flex;
      align-items: center;
      margin-top: 12px;
      justify-content: space-between;
      .title-text {
        font-size: 14px;
        // font-weight: bold;
        border-left: solid 2px #1890ff;
        padding-left: 8px;
        color: rgba(46, 46, 46);
      }
      .text {
        background: #fff;
        padding: 3px 6px;
        border: 4px solid rgba(242, 242, 242);
        border-radius: 1px;
        font-size: 14px;
      }
      // .title-action {
      //   border: 1px solid rgba(0, 0, 0, 0.1);
      //   padding: 1px 6px;
      //   cursor: pointer;
      //   border-radius: 2px;
      //   box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.1);
      // }
    }
    .top-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
      gap: 1vw;
      margin: 14px 0px;
      :deep(.summary-card) {
        display: flex;
        flex-direction: column;
        box-shadow: 7px 0 30px -3px rgba(0, 0, 0, 0.1) !important;
        .ant-card-body {
          flex: 1;
          display: flex;
          flex-direction: column;
          padding: 0 0px;
          overflow: hidden;
          .card-inner {
            flex: 1;
            display: flex;
            position: relative;
            z-index: 1;
            padding: 16px 12px;
            &::after,
            &::before {
              position: absolute;
              z-index: -1;
              content: '';
              width: 120px;
              height: 100%;
              transition: 0.3s linear;
              opacity: 0;
            }
            &::before {
              top: -15px;
              left: -20px;
              border-radius: 0 0 90px 0;
              background: #d3e8ff;
            }
            &::after {
              bottom: -43%;
              right: -10%;
              border-radius: 80px 0 0 0;
              background: #f2f8ff;
            }
            &:hover {
              &::before,
              &::after {
                opacity: 1;
              }
            }
            .card-left {
              flex: 2.5;
              display: flex;
              flex-direction: column;
              justify-content: space-between;
              .card-title {
                font-size: 14px;
                flex: 0 0 auto;
                .sub {
                  font-size: 14px;
                }
              }
              .card-value {
                font-size: 18px;
                font-weight: bold;
                color: #40a9ff;
                margin-top: 4px;
                flex: 0 0 auto;
              }
            }
            .card-right {
              width: 3vw;
              display: flex;
              align-items: center;
              .icon {
                width: 100%;
              }
            }
          }
        }
      }
    }
    .middle-charts {
      display: flex;
      align-items: center;
      gap: 0.8vw;
      :deep(.chart-box) {
        flex: 1;
        .ant-card-body {
          padding: 1.2vh 0.8vw 1.4vh;
          .title {
            margin-top: 0px;
            .title-text {
              font-size: 14px;
              border-left: none;
              padding-left: 0;
            }
            .ant-select {
              .ant-select-selector {
                border-radius: 2px;
              }
            }
          }
          .chart-content {
            height: 380px;
          }
        }
      }
    }
  }
  .divider {
    background-color: rgba(238, 244, 255);
    height: 2vh;
  }
  :deep(.ant-card) {
    border-radius: 4px;
  }
}
</style>
